import { mapGetters } from 'vuex'
import { DBNames } from '@/enum/dbName'
import { deepCopy } from '@/utils/tool'
import { ActionsType as PortalActionsType } from '@/actions/portal'
import {
  pageList,
  IPageListParams,
  upsertNoRecover,
  IUpsertParams,
  aggregate,
  IAggregateParams,
} from '@/api/commonInstance'

export interface IDraggableParams {
  templateName: string
  formKey: string
}
export default (params: IDraggableParams) => {
  const { templateName, formKey } = params
  const mixin = {
    props: {
      idList: {
        type: Array,
        default: () => [],
      },
      selectCount: {
        type: Number,
        default: 0,
      },
      total: {
        type: Number,
        default: 0,
      },
    },
    data() {
      return {
        loading: false,
        selectDataList: [],
        totalCount: 0,
        form: {
          [formKey]: [],
        },
      }
    },
    computed: {
      // visible: {
      //   get(): boolean {
      //     // @ts-ignore
      //     return this.showSelect
      //   },
      //   set(val: boolean) {
      //     // @ts-ignore
      //     this.$emit('update:showSelect', val)
      //   },
      // },
      ...mapGetters('portal', ['portalId', 'portalData']),
      ...mapGetters('user', ['orgId']),
    },
    watch: {
      idList(val: string[]) {
        // @ts-ignore
        this.form[formKey] = val
      },
      [`form.${formKey}`](arr: []) {
        // if (arr.length > -1) {
        // @ts-ignore
        this.update()
        // @ts-ignore
        this.fetchData()
        // }
      },
      // [`form.${formKey}`]: {
      //   immediate: true,
      //   handler() {
      //     // @ts-ignore
      //     this.update()
      //     // @ts-ignore
      //     this.fetchData()
      //   },
      // },
      portalId: {
        immediate: true,
        handler(id: number) {
          if (id) {
            console.log('初始化')

            // @ts-ignore
            this.initForm(this.portalData)
            // @ts-ignore
            this.$emit('update:idList', this.form[formKey])
          }
        },
      },
    },
    methods: {
      initForm(data: any) {
        // @ts-ignore
        this.formAll = deepCopy(data)
        const { form } = this as any
        Object.keys(form).forEach((key) => {
          // @ts-ignore
          const value = this.formAll[key]
          if (value) {
            form[key] = value
          }
        })
        // @ts-ignore
        console.log(this.form)
      },

      async fetchData() {
        // @ts-ignore
        const ids = this.form[formKey]
        const paramsList: IPageListParams = {
          conditions: {
            _id: { $in: ids.map((d: string) => `NumberLong(${d})`) },
          },
          pageInfo: { pageNum: 1, pageSize: 1000 },
          templateName: DBNames[templateName],
        }

        const paramsCount: IAggregateParams = {
          cmdList: [{ $count: 'total' }],
          templateName: DBNames[templateName],
        }

        // @ts-ignore
        this.loading = true
        // @ts-ignore
        const { list } = await pageList(paramsList)
        // @ts-ignore
        this.selectDataList = list.sort((a, b) => {
          const aIndex = ids.findIndex((d: string) => d === a.id)
          const bIndex = ids.findIndex((d: string) => d === b.id)
          return aIndex - bIndex
        })
        const result: any = await aggregate(paramsCount)

        if (result) {
          const [{ total }] = result
          // @ts-ignore
          this.totalCount = total
          // @ts-ignore
          this.$emit('update:selectCount', list.length)
          // @ts-ignore
          this.$emit('update:total', total)
        } else {
          // @ts-ignore
          this.totalCount = 0
          // @ts-ignore
          this.$emit('update:selectCount', 0)
          // @ts-ignore
          this.$emit('update:total', 0)
        }
        // @ts-ignore
        this.loading = false
      },

      async update() {
        // @ts-ignore
        const { portalId, form } = this
        if (!portalId) return
        const params: IUpsertParams = {
          id: portalId,
          data: { ...form },
          templateName: DBNames.B_CONSOLE_PARK,
        }
        await upsertNoRecover(params)
        // @ts-ignore
        this.$store.dispatch(PortalActionsType.getPortalById, portalId)
      },

      handleCheckedChange(row: any) {
        const { id, _id } = row
        // @ts-ignore
        const ids = this.form[formKey]
        const index = ids.findIndex((d: string) => d === id || d === _id)
        ids.splice(index, 1)
      },

      handleEnd() {
        // @ts-ignore
        const newIds = this.selectDataList.map((d) => d.id || d._id)
        // @ts-ignore
        this.form[formKey] = newIds
      },

      handleSelect() {
        // @ts-ignore
        this.$refs.select.open()
      },

      getFirstImage(row: any) {
        return (
          (row.data.imgList && row.data.imgList[0] && row.data.imgList[0].url) ||
          'https://fakeimg.pl/42x42/'
        )
      },
    },
  }

  return mixin
}
